package com.store.satring.web;
import com.store.satring.dos.Invoice;
import com.store.satring.dos.Item;
import com.store.satring.dos.ItemDetail;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.joda.time.format.DateTimeFormat;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.util.UriUtils;
import org.springframework.web.util.WebUtils;

@RequestMapping("/itemdetails")
@Controller
public class ItemDetailController {

	@RequestMapping(method = RequestMethod.POST, produces = "text/html")
    public String create(@Valid ItemDetail itemDetail, BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest) {
		Long invoiceId = itemDetail.getInvoiceId();
        if (bindingResult.hasErrors()) {
            populateEditForm(uiModel, itemDetail);
            return "itemdetails/create";
        }
        uiModel.asMap().clear();
        itemDetail.setQuantity(itemDetail.getQuantity() == null ? 0 : itemDetail.getQuantity());
        itemDetail.persist();
        Invoice invoice = Invoice.findInvoice(invoiceId);
        invoice.getItemDetails().add(itemDetail);
        invoice.persist();
        String storeInvoiceURL = (String) httpServletRequest.getSession().getAttribute("StoreInvoiceURL");
        if(storeInvoiceURL != null && !storeInvoiceURL.equals("")){
        	httpServletRequest.getSession().removeAttribute("StoreInvoiceURL");
        	return "redirect:invoices?"+storeInvoiceURL;
        }
        return "redirect:invoices/"+invoice.getId()+"?form";
    }

	@RequestMapping(params = "form", produces = "text/html")
    public String createForm(Model uiModel, HttpServletRequest httpServletRequest) {
		ItemDetail itemDetail = new ItemDetail();
		String invoiceId = httpServletRequest.getParameter("invoiceId");
		itemDetail.setInvoiceId(Long.parseLong(invoiceId));
		itemDetail.setRentedOn(new Date());
        populateEditForm(uiModel, itemDetail);
        List<String[]> dependencies = new ArrayList<String[]>();
        if (Item.countItems() == 0) {
            dependencies.add(new String[] { "item", "items" });
        }
        uiModel.addAttribute("dependencies", dependencies);
        return "itemdetails/create";
    }

	@RequestMapping(value = "/{id}", produces = "text/html")
    public String show(@PathVariable("id") Long id, Model uiModel) {
        addDateTimeFormatPatterns(uiModel);
        uiModel.addAttribute("itemdetail", ItemDetail.findItemDetail(id));
        uiModel.addAttribute("itemId", id);
        return "itemdetails/show";
    }

	@RequestMapping(produces = "text/html")
    public String list(@RequestParam(value = "page", required = false) Integer page, @RequestParam(value = "size", required = false) Integer size, @RequestParam(value = "sortFieldName", required = false) String sortFieldName, @RequestParam(value = "sortOrder", required = false) String sortOrder, Model uiModel) {
        if (page != null || size != null) {
            int sizeNo = size == null ? 10 : size.intValue();
            final int firstResult = page == null ? 0 : (page.intValue() - 1) * sizeNo;
            uiModel.addAttribute("itemdetails", ItemDetail.findItemDetailEntries(firstResult, sizeNo, sortFieldName, sortOrder));
            float nrOfPages = (float) ItemDetail.countItemDetails() / sizeNo;
            uiModel.addAttribute("maxPages", (int) ((nrOfPages > (int) nrOfPages || nrOfPages == 0.0) ? nrOfPages + 1 : nrOfPages));
        } else {
            uiModel.addAttribute("itemdetails", ItemDetail.findAllItemDetails(sortFieldName, sortOrder));
        }
        addDateTimeFormatPatterns(uiModel);
        return "itemdetails/list";
    }

	@RequestMapping(method = RequestMethod.PUT, produces = "text/html")
    public String update(@Valid ItemDetail itemDetail, BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest) {
        if (bindingResult.hasErrors()) {
            populateEditForm(uiModel, itemDetail);
            return "itemdetails/update";
        }
		String invoiceId = httpServletRequest.getParameter("invoiceId");
        uiModel.asMap().clear();
        itemDetail.setQuantity(itemDetail.getQuantity() == null ? 0 : itemDetail.getQuantity());
        itemDetail.merge();
        String storeInvoiceURL = (String) httpServletRequest.getSession().getAttribute("StoreInvoiceURL");
        if(storeInvoiceURL != null && !storeInvoiceURL.equals("")){
        	httpServletRequest.getSession().removeAttribute("StoreInvoiceURL");
        	return "redirect://invoices?"+storeInvoiceURL;
        }
        return "redirect:invoices/"+invoiceId+"?form";
    }

	@RequestMapping(value = "/{id}", params = "form", produces = "text/html")
    public String updateForm(@PathVariable("id") Long id, Model uiModel, HttpServletRequest httpServletRequest) {
		String invoiceId = httpServletRequest.getParameter("invoiceId");
		ItemDetail itemDetail = ItemDetail.findItemDetail(id);
		itemDetail.setInvoiceId(Long.parseLong(invoiceId));
        populateEditForm(uiModel, itemDetail);
        return "itemdetails/update";
    }
	@RequestMapping(value = "/{id}", method = RequestMethod.DELETE, produces = "text/html")
    public String delete(@PathVariable("id") Long id, Model uiModel, HttpServletRequest httpServletRequest ) {
        ItemDetail itemDetail = ItemDetail.findItemDetail(id);
        uiModel.asMap().clear();
		String invoiceId = httpServletRequest.getParameter("invoiceId");
		Invoice invoice = Invoice.findInvoice(Long.parseLong(invoiceId));
		invoice.getItemDetails().remove(itemDetail);
		invoice.persist();
        itemDetail.remove();
        String storeInvoiceURL = (String) httpServletRequest.getSession().getAttribute("StoreInvoiceURL");
        if(storeInvoiceURL != null && !storeInvoiceURL.equals("")){
        	httpServletRequest.getSession().removeAttribute("StoreInvoiceURL");
        	return "redirect://invoices?"+storeInvoiceURL;
        }
        return "redirect://invoices/"+invoiceId+"?form";
    }

	void addDateTimeFormatPatterns(Model uiModel) {
        uiModel.addAttribute("itemDetail_rentedon_date_format", DateTimeFormat.patternForStyle("M-", LocaleContextHolder.getLocale()));
    }

	void populateEditForm(Model uiModel, ItemDetail itemDetail) {
        uiModel.addAttribute("itemDetail", itemDetail);
        addDateTimeFormatPatterns(uiModel);
        uiModel.addAttribute("items", Item.findAllItems());
    }

	String encodeUrlPathSegment(String pathSegment, HttpServletRequest httpServletRequest) {
        String enc = httpServletRequest.getCharacterEncoding();
        if (enc == null) {
            enc = WebUtils.DEFAULT_CHARACTER_ENCODING;
        }
        try {
            pathSegment = UriUtils.encodePathSegment(pathSegment, enc);
        } catch (UnsupportedEncodingException uee) {}
        return pathSegment;
    }
}
